$(function () {
    class Register {
        constructor() {
            this.username = $("#username");
            this.password = $("#password");
            this.rpassword = $("#rpassword");
            this.register_btn = $("#registerbtn");
            // 提示框 ; 
            this.alert = $("#register-alert");
            this.bindEvent();
        }

        bindEvent() {
            $("#registerbtn").click(() => {
                this.register();
            })
        }
        register() {
            $.ajax({
                url: "http://127.0.0.1:8888/users/register",
                data: {
                    username: this.username.val(),
                    nickname: this.username.val(),
                    password: this.password.val(),
                    rpassword: this.rpassword.val()
                },
                type: "POST",
                success: function (res) {
                    return res;
                }
            })
            .then(res => {
                switch (res.code) {
                    case 0:
                        this.error(res);
                        break;
                    case 1:
                        this.success();
                        break;
                }
            })
        }
        error(res) {
            this.alert.removeClass("alert-success", "alert-danger");
            this.alert.addClass("alert-danger");
            this.alert.html("抱歉注册失败 : " + res.message)

            setTimeout(() => {
                this.alert.removeClass("alert-success", "alert-danger");
            }, 2000)
        }
        success() {
            this.alert.removeClass("alert-success", "alert-danger");
            this.alert.addClass("alert-success");
            this.alert.html("恭喜注册成功稍后我们将为您跳转登录页面");

            setTimeout(() => {
                location.href = "./login.html";

                sessionStorage.setItem("usermsg", JSON.stringify({
                    username: this.username.val(),
                    password: this.password.val()
                }));
            }, 2000)
        }
    }

    let r = new Register;
})